<template>
  <div id="container"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as Cesium from 'cesium';
import CesiumNavigation from 'cesium-navigation-es6';

import { initViewer, CesiumNavigationOptions } from './cesium/initViewer';
import { modifyMap } from './cesium/modifyMap';
import { modifyBuild } from './cesium/modifyBuild';
import LightCone from './cesium/Lightcone';
import RectFlyLight from './cesium/RectFlyLight';
import RoadLightLine from './cesium/RoadLightLine';
import RadartLight from './cesium/RadartLight';
import LightSpread from './cesium/LightSpread';
import LightWall from './cesium/LightWall';

import MousePosition from './cesium/MousePosition';
import './Widgets/widgets.css';

// 设置cesium 静态资源路径
window.CESIUM_BASE_URL = '/';
Cesium.Ion.defaultAccessToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNDkwYWVhOS0wNzI5LTQ3OTEtOWFiMC1kY2M3MTFiM2I2NWQiLCJpZCI6MTkyNTU1LCJpYXQiOjE3MDY1MTM0MTh9.YAPVHr1d7PBuWayCXM9deCxKg3AbtsXUJiVpubVS3NY';

onMounted(async () => {
  // const viewer = initViewer();
  const viewer = new Cesium.Viewer('container', {
    shouldAnimate: true,
  });

  // 根据鼠标位置生成经纬度值
  const mousePosition = new MousePosition(viewer);

  //如需自定义罗盘控件，请看下面的自定义罗盘控件
  new CesiumNavigation(viewer, CesiumNavigationOptions);

  //Make sure viewer is at the desired time.
  const start = Cesium.JulianDate.fromDate(new Date(2024, 2, 5, 16));
  const totalSeconds = 30;
  const stop = Cesium.JulianDate.addSeconds(
    start,
    totalSeconds,
    new Cesium.JulianDate()
  );
  viewer.clock.startTime = start.clone();
  viewer.clock.stopTime = stop.clone();
  viewer.clock.currentTime = start.clone();
  viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
  viewer.timeline.zoomTo(start, stop);

  // Create a path for our model by lerping between two positions.
  const position = new Cesium.SampledPositionProperty();
  const distance = new Cesium.SampledProperty(Number);
  const startPosition = new Cesium.Cartesian3(
    -2379556.799372864,
    -4665528.205030263,
    3628013.106599678
  );
  const endPosition = new Cesium.Cartesian3(
    -2379603.7074103747,
    -4665623.48990283,
    3627860.82704567
  );
  // A velocity vector property will give us the entity's speed and direction at any given time.
  const velocityVectorProperty = new Cesium.VelocityVectorProperty(
    position,
    false
  );
  const velocityVector = new Cesium.Cartesian3();

  const numberOfSamples = 100;
  let prevLocation = startPosition;
  let totalDistance = 0;
  for (let i = 0; i <= numberOfSamples; ++i) {
    const factor = i / numberOfSamples;
    const time = Cesium.JulianDate.addSeconds(
      start,
      factor * totalSeconds,
      new Cesium.JulianDate()
    );

    // Lerp using a non-linear factor so that the model accelerates.
    const locationFactor = Math.pow(factor, 2);
    const location = Cesium.Cartesian3.lerp(
      startPosition,
      endPosition,
      locationFactor,
      new Cesium.Cartesian3()
    );
    position.addSample(time, location);
    distance.addSample(
      time,
      (totalDistance += Cesium.Cartesian3.distance(location, prevLocation))
    );
    prevLocation = location;
  }

  function updateSpeedLabel(time, result) {
    velocityVectorProperty.getValue(time, velocityVector);
    const metersPerSecond = Cesium.Cartesian3.magnitude(velocityVector);
    const kmPerHour = Math.round(metersPerSecond * 3.6);

    return `${kmPerHour} km/hr`;
  }

  // 添加3D模型
  // const airplan = viewer.entities.add({
  //   name: 'airplan',
  //   position: Cesium.Cartesian3.fromDegrees(113.3191, 23.109, 700),
  //   // API https://cesium.com/learn/cesiumjs/ref-doc/ModelGraphics.html
  //   model: {
  //     uri: './model/Cesium_Man.glb',
  //     // uri: './model/Cesium_Air.glb',
  //     // uri: './model/bird.glb',
  //     minimumPixelSize: 128, // 最小像素
  //     silhouetteSize: 2, //轮廓
  //     silhouetteColor: Cesium.Color.WHITE, //轮廓的颜色
  //     // 设置相机距离模型多远的距离 显示该模型 api https://cesium.com/learn/cesiumjs/ref-doc/ModelGraphics.html
  //     distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
  //       0,
  //       200 * 1000
  //     ),
  //   },
  // });

  // Add our model.
  try {
    // const modelPrimitive = viewer.scene.primitives.add(
    //   new Cesium.Model.fromGltf({
    //     url: './model/bird.glb',
    //     // url: './model/Cesium_Man.glb',
    //     scale: 4,
    //     show: true,
    //   })
    //   // await Cesium.Model.fromGltfAsync({
    //   //   url: '/apiCesium/SampleData/models/CesiumMan/Cesium_Man.glb',
    //   //   // url: '../SampleData/models/CesiumMan/Cesium_Man.glb',
    //   //   scale: 4,
    //   // })
    // );

    viewer.scene.primitives.add(
      new Cesium.Model.fromGltf({
        url: './model/bird.glb', // 模型路径
        show: true,
        modelMatrix: new Cesium.Cartesian3(
          -2379556.799372864,
          -4665528.205030263,
          3628013.106599678
        ),
        scale: 1.0, // 模型缩放比例
        minimumPixelSize: 12, // 模型的最小像素大小
        maximumScale: 20000, // 模型的最大缩放比例
        allowPicking: false, // 是否允许鼠标选取
        debugShowBoundingVolume: false, // 是否显示模型的包围盒
        debugWireframe: false, // 是否以线框模式渲染模型
        color: Cesium.Color.YELLOW.withAlpha(0.5),
        colorBlendMode: Cesium.ColorBlendMode.MIX, // 设置颜色的混合模式
      })
    );

    // modelPrimitive.readyEvent.addEventListener(() => {
    //   modelPrimitive.activeAnimations.addAll({
    //     loop: Cesium.ModelAnimationLoop.REPEAT,
    //     animationTime: function (duration) {
    //       return distance.getValue(viewer.clock.currentTime) / duration;
    //     },
    //     multiplier: 0.25,
    //   });
    // });

    const rotation = new Cesium.Matrix3();
    // viewer.scene.preUpdate.addEventListener(function () {
    //   const time = viewer.clock.currentTime;
    //   const pos = position.getValue(time);
    //   const vel = velocityVectorProperty.getValue(time);
    //   Cesium.Cartesian3.normalize(vel, vel);
    //   Cesium.Transforms.rotationMatrixFromPositionVelocity(
    //     pos,
    //     vel,
    //     viewer.scene.globe.ellipsoid,
    //     rotation
    //   );
    //   Cesium.Matrix4.fromRotationTranslation(
    //     rotation,
    //     pos,
    //     modelPrimitive.modelMatrix
    //   );
    // });
  } catch (error) {
    // window.alert(error);
    console.log(error);
  }

  const modelLabel = viewer.entities.add({
    position: position,
    orientation: new Cesium.VelocityOrientationProperty(position), // Automatically set the model's orientation to the direction it's facing.
    label: {
      text: new Cesium.CallbackProperty(updateSpeedLabel, false),
      font: '20px sans-serif',
      showBackground: true,
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 100.0),
      eyeOffset: new Cesium.Cartesian3(0, 7.2, 0),
    },
  });
  viewer.trackedEntity = modelLabel;
  modelLabel.viewFrom = new Cesium.Cartesian3(-30.0, -10.0, 10.0);
});
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
}
#container {
  height: 90vh;
  width: 90vw;
}
</style>
